package cn.wmw.xyy.exception;

import cn.wmw.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获Exception异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public JsonResult exceptionHandler(Exception e){
        if (e.getClass().getSimpleName().equals("AccessDeniedException")){
            log.error("触发Exception异常，异常信息如下：{}",e.getMessage());
            return JsonResult.error(GlobalExceptionEnum.NO_PERMISSION_ERROR.getMessage(),GlobalExceptionEnum.NO_PERMISSION_ERROR.getCode());
        }
        e.printStackTrace();
        log.error("触发Exception异常，异常信息如下：{}",e.getMessage());
        return JsonResult.error(GlobalExceptionEnum.ERROR.getMessage(),GlobalExceptionEnum.ERROR.getCode());
    }

    /**
     * 捕获GlobalException异常
     * @param e
     * @return
     */
    @ExceptionHandler(GlobalException.class)
    public JsonResult globalExceptionHandler(GlobalException e){
        e.printStackTrace();
        log.error("触发GlobalException异常，异常信息如下：{},{}",e.getMessage(),e.getCode());
        return JsonResult.error(e.getMessage(),e.getCode());
    }

    /**
     * 捕获GlobalException异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        log.error("触发GlobalException异常，异常信息如下：{},{}",e.getMessage(),GlobalExceptionEnum.PARAM_VALIDATION_EXCEPTION.getCode());
        StringBuffer sb = new StringBuffer();
        e.getBindingResult().getAllErrors().forEach(error->sb.append(error.getDefaultMessage()).append(";"));
        return JsonResult.error(sb.toString(),GlobalExceptionEnum.PARAM_VALIDATION_EXCEPTION.getCode());
    }

}
